function checkListById(list, id) {
  // list 要检查的数据是空肯定没有
  if(!list.length) return false
  for (let index = 0; index < list.length; index++) {
     if(list[index].id === id) return list[index]
  }
  return false
}

export default {
  namespaced: true,
  state() {
    return {
      shopCarList: []
    }
  },
  getters: {
    allInfo(state) {
      let num = 0;
      let price = 0;
      state.shopCarList.map(item => {
        num += item.num 
        price += item.num * item.price
        return item
      })
      return { num, price}
    }
  },
  mutations: {
    addCar(state,goodsInfo) {
      const { name, id, price } = goodsInfo;
      // 该商品是否存在
      const isHave = checkListById(state.shopCarList,id)
      console.log(isHave)
      // 商品在购物车中存在数量++
      if(isHave) {
        isHave.num ++
      } else {
      // 商品在购物车中不存在push 新的并且数量是1
        state.shopCarList.push({
          name,id,price, num:1
        })
      }
    },
    decreateCar(state,payload) {
      console.log(111,payload)
      // 需要减少的商品id 和数量
      let {num ,id} = payload
      const havaInfo = checkListById(state.shopCarList,id)
      if(!havaInfo) return false
      if(havaInfo.num <= num) {
        alert("数量不足")
        return
      } 
      havaInfo.num -= num
    },
    increateCar(state,payload) {

      let {num ,id} = payload
      const havaInfo = checkListById(state.shopCarList,id)
      if(!havaInfo) return false
      havaInfo.num += num
    }
  }
}

